package com.example.weather.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.example.weather.Adapter.GridViewAdapter;
import com.example.weather.R;
import com.example.weather.interfaceimpl.DynamicListItemOperator;
import com.example.weather.utils.AppUtils;
import com.example.weather.utils.ConstantsUtil;
import com.example.weather.utils.NetWorkUtils;
import com.example.weather.utils.SharePreferenceManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ChangeCityActivity extends AppCompatActivity {
    private ArrayList<String> mCityArrayList;
    private AutoCompleteTextView mSerachProvince;
    private ArrayAdapter adapter;
    private String[] mProvence;
    private Button mSubmit;
    private final String mKey = "exv7a60meq94rybh";
    private int limit = 10;
    private int offset = 0;
    private Handler handler;
    private String mSearchProvince;
    private ListView mSearchCityListView;
    private GridViewAdapter mGridViewAdapter;
    private ArrayList<Map<String,Object>> mPullListViewArrayList;
    private ProgressDialog mProgressBar;
    private RelativeLayout mTitleRelativeLayout;
    private int[] mScreenAidthAndHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_city);
        InitData();
        InitView();
    }

    private void InitData(){
        mCityArrayList = new ArrayList<>();
        mPullListViewArrayList = new ArrayList<>();
        mProvence = getResources().getStringArray(R.array.provenceArray);
        adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, mProvence);
        mScreenAidthAndHeight = AppUtils.getScreenHeightAndWidth(this);
    }

    private void InitView(){
        mProgressBar = new ProgressDialog(this);
        mProgressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressBar.setTitle("加载中");
        mProgressBar.setMessage("请耐心等待.....");
        mSerachProvince = (AutoCompleteTextView) findViewById(R.id.actv_search_Province);
        mSubmit = (Button) findViewById(R.id.bt_submit);
        mSearchCityListView = (ListView) findViewById(R.id.lv_select_city);
        mTitleRelativeLayout = (RelativeLayout) findViewById(R.id.rl_title);
        mTitleRelativeLayout.getLayoutParams().height = (int)(mScreenAidthAndHeight[1] * 0.1);
        mGridViewAdapter = new GridViewAdapter(this, mPullListViewArrayList,new DynamicListItemOperator(),handler);
        mSearchCityListView.setAdapter(mGridViewAdapter);
        mSearchCityListView.setOnItemClickListener(new ItemClickListener());

        mSerachProvince.setAdapter(adapter);
        ClickListener clickListener = new ClickListener();
        mSubmit.setOnClickListener(clickListener);
        handler = new MyHandler();
    }

    //继承OnItemClickListener，当子项目被点击的时候触发
    private class ItemClickListener  implements AdapterView.OnItemClickListener{
        @Override
        //这里需要注意的是第三个参数arg2，这是代表单击第几个选项
        public void onItemClick(AdapterView<?> parent, View view, int positon,
                                long id) {
            final Map<String, Object> map = mPullListViewArrayList.get(positon);
            AlertDialog.Builder builder = new AlertDialog.Builder(ChangeCityActivity.this);
            builder.setMessage("确定切换城市吗？");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    SharePreferenceManager.setDefaultCity(getApplicationContext(),(String)map.get("city"));
                    finish();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    }

    private class ClickListener implements View.OnClickListener {
        public void onClick(View v) {
            if (v.getId() == R.id.bt_submit) {
                mProgressBar.show();
                mPullListViewArrayList.clear();
                offset = 0;
                mSearchProvince = mSerachProvince.getText().toString();
                String params = "key="+mKey+"&q="+ mSearchProvince+"&limit="+limit+"&offset="+offset;
                NetWorkUtils.sendMessageByGet(ConstantsUtil.Get_City_Info,params,handler,ConstantsUtil.Get_City_Message_Message_Id);
            }
        }
    }

    public class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == ConstantsUtil.Get_City_Message_Message_Id) {
                handleGetClubActivityMessage(msg);
            }
        }

        private void handleGetClubActivityMessage(Message msg){
            try{
                String obj = msg.obj.toString();
                JSONObject message = new JSONObject(obj);
                JSONArray resultsJSONArray = message.getJSONArray("results");
                JSONObject result;
                Map<String,Object> map = new HashMap<>();
                for(int i=0;i< resultsJSONArray.length();i++){
                    result = resultsJSONArray.getJSONObject(i);
                    map.put("city",result.getString("name"));
                    mPullListViewArrayList.add(map);
                    map = new HashMap<>();
                }
                if(resultsJSONArray.length() == limit){
                    offset+=limit;
                    String params = "key="+mKey+"&q="+ mSearchProvince +"&limit="+limit+"&offset="+offset;
                    NetWorkUtils.sendMessageByGet(ConstantsUtil.Get_City_Info,params,handler,ConstantsUtil.Get_City_Message_Message_Id);
                }else{
                    mGridViewAdapter.notifyDataSetChanged();
                    mProgressBar.cancel();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
